﻿CREATE proc [dbo].[proc_Customer_Audit]
(
	@CustomerId uniqueidentifier,
	@UserName nvarchar(50)
)
As
Begin
	Declare @CustomerName nvarchar(50),@SalesName nvarchar(50),@CreateName nvarchar(50),@ProtectName nvarchar(50)
	Declare @CompanyId int,@ProtectId int,@Extract int
	
	Select @CompanyId=CompanyId,@CustomerName=CustomerName,@ProtectId=ProtectId,@CreateName=CreateName,@ProtectName=ProtectName From Customer Where CustomerId=@CustomerId
	If @CompanyId Is Null Or @CustomerName Is Null
		Return 0	--该数据已经不存在(被其他审核人删除了)
	
	If @ProtectId=2 Or @ProtectId=4	--保护或跟踪
		Begin
			Set @SalesName=@ProtectName
			Update Customer Set Audit=1,AuditPerson=Null,ProtectDate=GetDate() Where CustomerId=@CustomerId
		End
	Else If	@ProtectId=3	--已签单
		Begin
			Set @SalesName=@CreateName
			Update Customer Set Audit=1,AuditPerson=Null,ProtectName=Null,ProtectDate=Null,UpTime='1900-01-01' Where CustomerId=@CustomerId
		End
	Else	--公库
		Begin
			Set @SalesName=@CreateName
			Select @Extract=DateDiff(dd,'1900-1-1',GetDate())	--审批日期(今天)
			Update Customer Set Audit=1,AuditPerson=Null,ProtectName=@CreateName,ProtectDate=Null,UpTime='1900-01-01',ExtractDate=@Extract+1 Where CustomerId=@CustomerId
		End

	Insert Into Customer_Auditlog(CustomerId,CustomerName,Description,AuditUser,AuditDate,Type,CompanyId,SalesName)
	Values(@CustomerId,@CustomerName,'通过',@UserName,GetDate(),1,@CompanyId,@SalesName)

	Return 1
End